<template>
  <!-- <div height="20px"></div> -->
  <div>
    <el-container>
      <el-header>
        <h1>构建密文数据库</h1>
      </el-header>
      <el-main>
        <el-row></el-row>
        <el-row></el-row>
        <el-row :gutter="12">
          <el-col :span="9" :offset="6">
            <!-- <el-input v-model="docPath" placeholder="请输入明文文档集路径" clearable>
              <template slot="append">
                <el-button icon="el-icon-search" @click.native="openFolderSelector">浏览</el-button>
              </template>
</el-input> -->
            <el-input v-model="selectedPath" placeholder="请输入明文文档集路径" clearable>
              <template #append>
                <!-- 触发文件夹选择的按钮 -->
                <el-button icon="el-icon-folder-opened" @click="openFolderSelector"></el-button>
              </template>
            </el-input>
            <input type="file" id="folderInput" webkitdirectory style="display: none;" @change="handleFolderSelect" />

          </el-col>
          <el-col :span="3">
            <el-button type="primary" @click="constructEncdb" style="width: 100%;">上传并构建</el-button>
          </el-col>
        </el-row>
        <el-row></el-row>
        <el-row :gutter="10">
          <el-col :span="10" :offset="7">
            构建进度：
            <el-progress :percentage="constructProgress"
              :status="constructProgress === 100 ? 'success' : null"></el-progress>
          </el-col>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="12" :offset="6">
            <el-card class="box-card" style="margin-top: 20px;">
              <div slot="header" class="clearfix">
                <span>构建日志</span>
              </div>
              <div class="build-logs">
                <div v-for="(log, index) in buildLogs" :key="index" class="log-item">
                  <div class="log-time">{{ log.time }}</div>
                  <div class="log-content">{{ log.content }}</div>
                </div>
                <div v-if="buildLogs.length === 0" class="no-logs">
                  暂无构建日志
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-main>

    </el-container>


  </div>
</template>

<script>
import fs from 'fs'
import { ipcRenderer } from "electron";
import axios from 'axios';

export default {
  data() {
    return {
      constructProgress: 100,
      selectedPath: 'D:\\workspace\\Project\\fhe-search\\encdb-files\\AllPlainData',
      buildLogs: [
        {
          "time": "2025-03-10 21:31:37",
          "content": "GenerateBigPlainDB start."
        },
        {
          "time": "2025-03-10 21:31:37",
          "content": "drop and create table plain_term/plain_index finished."
        },
        {
          "time": "2025-03-10 21:31:37",
          "content": "docs are processing: 1000"
        },
        {
          "time": "2025-03-10 21:31:37",
          "content": "docs are processing: 2000"
        },
        {
          "time": "2025-03-10 21:31:37",
          "content": "docs are processing: 3000"
        },
        {
          "time": "2025-03-10 21:31:37",
          "content": "docs are processing: 4000"
        },
        {
          "time": "2025-03-10 21:31:37",
          "content": "docs are processing: 5000"
        },
        {
          "time": "2025-03-10 21:31:37",
          "content": "docs are processing: 6000"
        },
        {
          "time": "2025-03-10 21:31:37",
          "content": "docs are processing: 7000"
        },
        {
          "time": "2025-03-10 21:31:37",
          "content": "docs are processing: 8000"
        },
        {
          "time": "2025-03-10 21:31:37",
          "content": "docs are processing: 9000"
        },
        {
          "time": "2025-03-10 21:31:37",
          "content": "docs are processing: 10000"
        },
        {
          "time": "2025-03-10 21:31:43",
          "content": "1000 docs have been cut. last doc_id: 14760. ShardedMap len: 115388."
        },
        {
          "time": "2025-03-10 21:31:53",
          "content": "2000 docs have been cut. last doc_id: 16847. ShardedMap len: 191052."
        },
        {
          "time": "2025-03-10 21:32:14",
          "content": "3000 docs have been cut. last doc_id: 13242. ShardedMap len: 244034."
        },
        {
          "time": "2025-03-10 21:32:41",
          "content": "4000 docs have been cut. last doc_id: 23587. ShardedMap len: 266590."
        },
      ] // 构建日志
    };
  },
  methods: {
    // 打开文件夹选择器
    openFolderSelector() {
      const folderInput = document.getElementById('folderInput');
      if (folderInput) {
        folderInput.click();
      } else {
        console.error('File input element not found');
      }
    },
    // 处理文件夹选择
    handleFolderSelect(event) {
      const selectedFolder = event.target.files[0];
      console.log(selectedFolder);
      console.log(selectedFolder.path);
      console.log(event.target)
      console.log(event)
      if (selectedFolder) {
        // 获取文件夹路径
        // this.selectedPath = selectedFile.webkitRelativePath.split('/')[0];
        this.selectedPath = selectedFolder.path;
      }
    },
    constructEncdb() {
      // TODO: 上传并构建密文数据库
      if (this.selectedPath == '') {
        this.$message({
          message: '请选择明文文档集路径！',
          type: 'warning'
        });
        return
      }
    },
    handleClose(term) {
      this.terms.splice(this.terms.indexOf(term), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.terms.push(
          {
            term: inputValue,
            freq: 1
          }
        );
      }
      this.inputVisible = false;
      this.inputValue = '';
    },

    beforeFileUpload(file) {
      fs.readFile(file.path, async (err, data) => {
        if (err) {
          console.error('Error reading the file:', err);
          return false;
        }
        this.$message({
          message: '正在读取文件，请稍后...',
        });
        this.file_title = file.name.split('.')[0];
        this.file_type = file.name.split('.')[1];
        // file_type 转小写
        this.file_type = this.file_type.toLowerCase();
        this.file_content_base64 = data.toString('base64');
        if (this.file_type == "txt") {
          this.file_content = data.toString();
        } else if (this.file_type == "pdf") {
          const resp = await axios.post('http://127.0.0.1:5000/GetTextFromPdf', {
            pdf_base64: this.file_content_base64
          })
          this.file_content = resp.data.text;
        }
        this.$message({
          message: '读取文件成功！',
          type: 'success'
        });
      });
      this.fileList.push(file);
      return true;
    },

    preview_file() {
      if (this.file_content_base64 == "") {
        this.$message({
          message: '请先上传文件！',
          type: 'warning'
        });
        return;
      }
      if (this.file_content == "") {
        this.$message({
          message: '请等待文件读取完成！',
          type: 'warning'
        });
        return;
      }
      this.preview_file_dialog_visible = true;
    },

    extract_keywords() {
      if (this.file_content_base64 == "") {
        this.$message({
          message: '请先上传文件！',
          type: 'warning'
        });
        return;
      }
      if (this.file_content == "") {
        this.$message({
          message: '请等待文件读取完成！',
          type: 'warning'
        });
        return;
      }
      ipcRenderer.invoke("ExtractKeywords", { content: this.file_content }).then((res) => {
        this.terms = res;
        this.extract_keywords_dialog_visible = true;
      });
    },

    customHttpRequest(file) {
      // 使用你喜欢的 HTTP 库（比如 Axios）来发起文件上传请求
      // 这里仅为演示，实际情况中需要根据你的后端 API 进行调整
      return true;
    },

    upload_encrypt_file() {
      if (this.file_content_base64 == "") {
        this.$message({
          message: '请先上传文件！',
          type: 'warning'
        });
        return;
      }
      if (this.file_content == "") {
        this.$message({
          message: '请等待文件读取完成！',
          type: 'warning'
        });
        return;
      }
      if (this.terms.length == 0) {
        this.$message({
          message: '请先提取关键词！',
          type: 'warning'
        });
        return;
      }
      if (this.file_title == "") {
        this.$message({
          message: '请输入文件标题！',
          type: 'warning'
        });
        return;
      }
      this.$message({
        message: '正在上传，请稍后...',
      });
      ipcRenderer.invoke("UploadEncFile", {
        title: this.file_title,
        content_base64: this.file_content_base64,
        file_type: this.file_type,
        terms: this.terms
      }).then((res) => {
        console.log(res);
        if (res) {
          this.$message({
            message: '上传密文文件成功！',
            type: 'success'
          });
        } else {
          this.$message({
            message: '上传密文文件失败！',
            type: 'error'
          });
        }
      });
    },
  }
}
</script>



<style>
.el-header {
  color: #333;
  text-align: center;
  line-height: 60px;
}

.el-tag+.el-tag {
  margin-left: 10px;
  margin-top: 8px;
}

.button-new-tag {
  margin-left: 10px;
}

.input-new-tag {
  margin-left: 10px;
  width: 90px;
}

.center-component {
  /* width: 500px; */
  margin-top: 20px;
  display: flex;
  justify-content: center;
  /* 水平居中 */
}

.build-logs {
  max-height: 300px;
  overflow-y: auto;
  padding: 10px;
}

.log-item {
  margin-bottom: 10px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.log-time {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.log-content {
  font-size: 14px;
  color: #303133;
}

.no-logs {
  text-align: center;
  color: #909399;
  padding: 20px 0;
}
</style>